unit Unit1;

interface

uses
  Windows, Messages, SysUtils, Variants, Classes, Graphics, Controls, Forms,
  Dialogs, StdCtrls, ExtCtrls;

const
  A = 5;
  N = 15;
  B = 50;

type
  TForm1 = class(TForm)
    ScrollBar1: TScrollBar;
    Timer1: TTimer;
    Button1: TButton;
    procedure Timer1Timer(Sender: TObject);
    procedure FormCreate(Sender: TObject);
    procedure Draw;
    procedure Button1Click(Sender: TObject);
    private
    { Private declarations }
  public
    { Public declarations }
  end;

var
  Form1: TForm1;
  arr: array [0..N] of TPanel;
  Step, runNumber: integer;
  flag: boolean;

implementation

{$R *.dfm}

procedure TForm1.Timer1Timer(Sender: TObject);
var t, i: integer;
begin
  if (step = 0) then
    flag:= true;
  Timer1.Interval:= ScrollBar1.Position;
  if (StrToInt(arr[step].Caption)>StrToInt(arr[step+1].Caption)) then
  begin
    t:= StrToInt(arr[step].Caption);
    arr[step].Caption:= arr[step+1].Caption;
    arr[step+1].Caption:= IntToStr(t);
    flag:= false;
  end;
  Draw;
  inc(step);
  if (step=N-1-runNumber) then
  begin
    step:= 0;
    inc(runNumber);
    if (runNumber=N-1) or (flag) then
      Timer1.Enabled:= false;
  end;
end;

procedure TForm1.FormCreate(Sender: TObject);
var i: integer;
begin
  randomize;
  Step:= 0;
  runNumber:= 0;
  for i:= 0 to N-1 do
  begin
    arr[i]:= TPanel.Create(Form1);
    arr[i].Parent:=Form1;
    arr[i].Width:= B;
    arr[i].Height:= B;
    arr[i].Top:= 0;
    arr[i].Left:= i*B;
    arr[i].Caption:= IntToStr(random(20));
  end;
  ScrollBar1.Min:= 1;
  Draw;

end;

procedure TForm1.Draw;
var i: integer;
begin
  for i := 0 to N-1 do
  begin
    if (i<N-runNumber) then
      arr[i].Color:= clWhite;
    if ((i=Step) and (i+1=Step+1)) or ((i=Step+1) and (i-1=Step)) then
      arr[i].Color:= clRed;
    if (i=N-runNumber) then
      arr[i].Color:= clBlue;
  end;
end;

procedure TForm1.Button1Click(Sender: TObject);
var i: integer;
begin
  Step:= 0;
  runNumber:= 0;
  for i:= 0 to N-1 do
    arr[i].Caption:= IntToStr(random(20));
  Timer1.Enabled:= true;
end;

end.

